package net.receiving;

import net.IncomingMessage;
import net.receiving.tcp.TCPServer;
import net.receiving.converter.Converter;

import java.util.concurrent.BlockingQueue;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.List;
import java.util.Map;
import java.net.InetAddress;

public class IncomingMessageTCPFactory implements IncomingMessageFactory {

    private final BlockingQueue<Map.Entry<InetAddress, List<Byte>>> queue;

    public IncomingMessageTCPFactory() {
        queue = new LinkedBlockingQueue<Map.Entry<InetAddress, List<Byte>>>();
        new Thread(new TCPServer(queue)).start();
    }

    public IncomingMessage receive() {
        List<Byte> list;
        InetAddress ip;
        try {
            Map.Entry<InetAddress, List<Byte>> temp = queue.take();
            list = temp.getValue();
            ip = temp.getKey();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        byte[] a = new byte[list.size()];
        int index = 0;
        for (byte x : list) {
            a[index] = x;
            index++;
        }
        return Converter.createIncomingMessage(a, a.length, ip);
    }
}
